package org.fpaadmin.web;

import java.util.Iterator;
import java.util.List;

import org.apache.wicket.markup.repeater.data.IDataProvider;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.LoadableDetachableModel;

public abstract class GenericDataProvider<T> implements IDataProvider<T> {

    private static final long serialVersionUID = 1L;
    
    private TemplatePage page;
    
    public GenericDataProvider(TemplatePage page) {
        this.page = page;
    }
    
    @Override
    public void detach() {
    }

    protected abstract Class<T> getGenericClass();
    
    @Override
    public Iterator<T> iterator(int first, int count) {
        List<T> objects = page.getEntityManager().createQuery("SELECT s FROM " + getGenericClass().getName() + " s", getGenericClass()).getResultList();
        return objects.iterator();
    }

    @Override
    public int size() {
        return page.getEntityManager().createQuery("SELECT COUNT(*) FROM " + getGenericClass().getName(), Long.class).getSingleResult().intValue();
    }

    @Override
    public IModel<T> model(T object) {
        return new DetachableGenericModel<T>(object);
    }
}

class DetachableGenericModel<T> extends LoadableDetachableModel<T> {

    private static final long serialVersionUID = 1L;
    
    private T model;
    
    public DetachableGenericModel(T generic)
    {
        this.model = generic;
    }
    
    @Override
    protected T load() {
        return model;
    }
    
}
